package com.bwie.filter;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.concurrent.TimeUnit;

/**
 * @author 军哥
 * @version 1.0
 * @description: 网关过滤器
 * @date 2024/10/17 15:22
 */
@Configuration
public class MyGlobalFilter implements GlobalFilter, Ordered {

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    /**
     * 加入有多个过滤器，决定过滤器的优先级别
     * 0 优先级最高，数值越大，优先级越低
     * @return
     */
    @Override
    public int getOrder() {
        return 0;
    }

    /**
     * 网关全局过滤器
     * @param exchange
     * @param chain
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //-- 获取参数
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        String url = request.getURI().getPath();
        System.out.println("请求路径："+url);
        String ip = request.getRemoteAddress().getAddress().toString();
        System.out.println("请求ip："+ip);

        //-- 白名单：不用登录，就可以访问的接口（登录接口、发送验证码、注册接口）
        // url 白名单
        if(url.contains("/login") || url.contains("/sendCode") || url.contains("/shoperRegister")){
            System.out.println("白名单，放行" + url);
            return chain.filter(exchange);
        }
        // ip 白名单（ip要写虚拟机的IP，是约定）
        if(ip.contains("192.168.80.192")){
            System.out.println("白名单，放行" + ip);
            return chain.filter(exchange);
        }

        //-- 获取请求的token
        String token = request.getHeaders().getFirst("token");
        if(token == null) {
            System.out.println("请求token为空，请先登录~~~~");
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        System.out.println("请求token："+token);

        //-- 校验token：是否合法
        Claims body = Jwts.parser().setSigningKey("123456").parseClaimsJws(token).getBody();
        Integer userId = body.get("userId", Integer.class);
        String tokenKey = "token-" + userId;
        String redisToken = stringRedisTemplate.opsForValue().get(tokenKey);
        if(redisToken == null) {
            System.out.println("token已过期，请重新登录~~~~");
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        if(!redisToken.equals(token)) {
            System.out.println("token不合法，请重新登录~~~~");
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }

        //-- token续期：续期30分钟
        stringRedisTemplate.expire(tokenKey, 30, TimeUnit.MINUTES);

        //-- 放行
        System.out.println("token合法，放行~~~~"+ url);

        return chain.filter(exchange);
    }


}
